package com.base.http

import okhttp3.*
import okhttp3.Response
import okio.Buffer
import java.net.URLDecoder
import java.nio.charset.Charset

/**
 * 请求拦截器
 */
object IInterceptor: Interceptor{
    private const val SIGNATURE_KEY = "MD5签名字段名"

    override fun intercept(chain: Interceptor.Chain): Response {
        return chain.proceed(newRequest(chain.request()))
    }

    private fun newRequest(request: Request): Request{
        val url = request.url()
        val method = request.method()

        if(!request.isHttps){
            if(method == "GET" || method == "DELETE"){
                return getRequest(url,request)
            }else{
                val body = request.body()

                if(body is MultipartBody){
                    return multipartRequest(method,request,body)
                }else if(body is FormBody){
                    return formRequest(method,request,body)
                }
            }
        }

        return addHeader(request.newBuilder()).build()
    }

    private fun getRequest(url: HttpUrl,request: Request): Request{
        val requestBuilder = request.newBuilder()
        val query = url.encodedQuery()
        if(query != null){
            val options = arrayListOf<String>()

            val list = query.split("&")
            for(option in list){
                val valueList = option.split("=")
                val key: String = valueList[0].trim()
                if(key == SIGNATURE_KEY) return request
                val value = valueList.getOrNull(1) ?: continue
                options.add("\"$key:$value\"")
            }

            if(options.size > 0) requestBuilder.url(url.newBuilder().addQueryParameter(SIGNATURE_KEY,MD5Signature.signature(options,url.toString())).build())
        }

        return requestBuilder.build()
    }

    private fun multipartRequest(method: String,request: Request,body: MultipartBody): Request{
        val builder = MultipartBody.Builder()
        val requestBuilder = request.newBuilder()
        addHeader(requestBuilder)
        val options = arrayListOf<String>()
        val charset = body.type().charset(Charset.forName("utf-8")) ?: Charset.forName("utf-8")

        for(part in  body.parts()){
            builder.addPart(part)
            val header = part.headers()?.get("Content-Disposition") ?: continue
            val list = header.split(";")
            if(list.size == 2){
                val buffer = Buffer()
                part.body().writeTo(buffer)
                val key: String = list[1].split("=")[1].trim()
                if(key.trim() == SIGNATURE_KEY.trim()) return requestBuilder.build()
                val value: String = URLDecoder.decode(buffer.readString(charset).trim(),"utf-8")
                options.add("\"$key:$value\"")
            }
        }



        if(options.size > 0){
            builder.addFormDataPart(SIGNATURE_KEY,MD5Signature.signature(options,request.url().toString()))
            requestBuilder.method(method,builder.build())
        }

        return requestBuilder.build()
    }

    private fun formRequest(method: String,request: Request,body: FormBody): Request{
        val requestBuilder = request.newBuilder()
        addHeader(requestBuilder)
        val builder = FormBody.Builder()
        val options = arrayListOf<String>()

        for(option in 0 until body.size()){
            val key = body.name(option)
            val value = body.value(option)
            if(key.trim() == SIGNATURE_KEY) return requestBuilder.build()
            builder.addEncoded(key,value)
            options.add("\"${key}:${value}\"")
        }

        if(options.size > 0){
            builder.addEncoded(SIGNATURE_KEY,MD5Signature.signature(options,request.url().toString()))
            requestBuilder.method(method,builder.build())
        }

        return requestBuilder.build()
    }

    /**
     * 添加全局请求头
     */
    private fun addHeader(builder: Request.Builder): Request.Builder{
//        if(AccountHelper.isLogin() && !AccountHelper.info.token.isNullOrEmpty()){
//            builder.addHeader("token",AccountHelper.info.token)
//        }
        return builder
    }



}